import { EditOutlined } from "@ant-design/icons";
import type { RedisClient, ValueScore } from "@linksaas-minapp/redis-proxy-api"
import { Button, Card, Descriptions, Form, Input, InputNumber, List, Modal, Space, message } from "antd"
import { useState, useEffect } from "react"

export interface SortedSetValueProps {
    client: RedisClient;
    curKey: string;
}

function SortedSetValue(props: SortedSetValueProps) {
    const [valueList, setValueList] = useState<ValueScore[]>([]);
    const [editScore, setEditScore] = useState(0.0);
    const [editScoreValue, setEditScoreValue] = useState("");
    const [newScore, setNewScore] = useState(0.0);
    const [newValue, setNewValue] = useState("");
    const [showAddModal, setShowAddModal] = useState(false);

    const loadData = async () => {
        const res = await props.client.sortedSetCommand().zscan(props.curKey, 0, "*", 9999);
        const resultList = [] as ValueScore[];
        if (Array.isArray(res)) {
            let tmpList = [] as string[];
            for (const v of (res[1] as string[])) {
                tmpList.push(v);
                if (tmpList.length == 2) {
                    resultList.push({
                        value: tmpList[0],
                        score: parseFloat(tmpList[1]),
                    });
                    tmpList = [];
                }
            }
        }
        setValueList(resultList);
    };

    const updateScore = async () => {
        await props.client.sortedSetCommand().zadd(props.curKey, [{
            value: editScoreValue,
            score: editScore,
        }], "XX");
        const tmpList = valueList.slice();
        const index = tmpList.findIndex(item => item.value == editScoreValue);
        if (index != -1) {
            tmpList[index].score = editScore;
            setValueList(tmpList);
        }
        setEditScore(0);
        setEditScoreValue("");
    };

    const removeData = async (value: string) => {
        await props.client.sortedSetCommand().zrem(props.curKey, [value]);
        const tmpList = valueList.filter(item => item.value != value);
        setValueList(tmpList);
    };

    const addData = async () => {
        try {
            await props.client.sortedSetCommand().zscore(props.curKey, newValue);
            message.warning("值已经存在");
        } catch (_e) {
            await props.client.sortedSetCommand().zadd(props.curKey, [{
                value: newValue,
                score: newScore,
            }]);
            const tmpList = valueList.slice();
            tmpList.unshift({
                value: newValue,
                score: newScore,
            });
            setValueList(tmpList);
            setShowAddModal(false);
            message.info("添加成功");
        }
    };

    useEffect(() => {
        loadData();
    }, []);

    return (
        <Card extra={
            <Button type="primary" onClick={e => {
                e.stopPropagation();
                e.preventDefault();
                setNewScore(0);
                setNewValue("");
                setShowAddModal(true);
            }}>添加值</Button>
        }>
            <List dataSource={valueList}
                style={{ height: "calc(100vh - 280px)", overflowY: "auto" }}
                renderItem={item => (
                    <List.Item key={item.value} extra={
                        <Button danger type="link" onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            removeData(item.value);
                        }}>删除</Button>
                    }>
                        <Descriptions column={2}>
                            <Descriptions.Item label="值" style={{ paddingBottom: "0px" }}>{item.value}</Descriptions.Item>
                            <Descriptions.Item label="分数" style={{ paddingBottom: "0px" }}>
                                <Space>
                                    {item.score}
                                    <a onClick={e => {
                                        e.stopPropagation();
                                        e.preventDefault();
                                        setEditScore(item.score);
                                        setEditScoreValue(item.value);
                                    }}><EditOutlined /></a>
                                </Space>
                            </Descriptions.Item>
                        </Descriptions>
                    </List.Item>
                )} />
            {editScoreValue != "" && (
                <Modal open title="修改分数" okText="修改"
                    onCancel={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setEditScore(0);
                        setEditScoreValue("");
                    }} width={250}
                    onOk={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        updateScore();
                    }}>
                    <Form>
                        <Form.Item label="分数">
                            <InputNumber style={{ width: "100%" }} value={editScore} precision={5} onChange={value => setEditScore(value ?? 0.0)} controls={false} />
                        </Form.Item>
                    </Form>
                </Modal>
            )}
            {showAddModal == true && (
                <Modal open title="添加值" okText="添加" okButtonProps={{ disabled: newValue == "" }} width={250}
                    onCancel={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setShowAddModal(false);
                    }}
                    onOk={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        addData();
                    }}>
                    <Form labelCol={{ span: 5 }}>
                        <Form.Item label="值">
                            <Input value={newValue} onChange={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setNewValue(e.target.value);
                            }} />
                        </Form.Item>
                        <Form.Item label="分数">
                            <InputNumber style={{ width: "100%" }} controls={false} onChange={value => setNewScore((value as number) ?? 0.0)} />
                        </Form.Item>
                    </Form>
                </Modal>
            )}
        </Card>
    );
}

export default SortedSetValue;